package com.kuaishou.locallife.open.api.common.utils;

import java.security.KeyFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.kuaishou.locallife.open.api.KsLocalLifeApiException;

/**
 * @author gaojiapei <gaojiapei@kuaishou.com>
 * Created on 2023-02-05
 */
public class SHAUtils {
    /**
     * 传入文本内容，返回 SHA-256 串
     */
    public static String sha256(final String strText) throws KsLocalLifeApiException {
        return sha(strText, "SHA-256");
    }

    /**
     * 传入文本内容，返回 SHA-512 串
     */
    public static String sha512(final String strText) throws KsLocalLifeApiException {
        return sha(strText, "SHA-512");
    }

    /**
     * 字符串 SHA 加密
     *
     * @param strText 原字符串
     */
    private static String sha(final String strText, final String strType) throws KsLocalLifeApiException {
        // 返回值
        String strResult = null;

        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                // 创建加密对象 并傳入加密類型
                MessageDigest messageDigest = MessageDigest.getInstance(strType);
                // 传入要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 類型结果
                byte[] byteBuffer = messageDigest.digest();

                // 將 byte 转为 string
                StringBuffer strHexString = new StringBuffer();
                // 遍历 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                // 得到返回結果
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                throw new KsLocalLifeApiException("SHAUtils sha error, str=" + strText, e);
            }
        }

        return strResult;
    }

    /**
     * 传入文本&私钥内容，返回 SHA1withRSA 串
     */
    public static String sha1withRSA(String data, String privateKey) throws Exception {
        byte[] resultByte = signWithSha(data.getBytes("UTF-8"), Base64.decodeBase64(privateKey), "SHA1withRSA");
        return Base64.encodeBase64String(resultByte);
    }

    private static byte[] signWithSha(byte[] data, byte[] privateKey, String algorithm) throws Exception {
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(algorithm);
        signature.initSign(priKey);
        signature.update(data);
        return signature.sign();
    }
}
